package com.xiaozhengkeji.mchttpapi;

import com.xiaozhengkeji.mchttpapi.tcp.TcpServer;
import com.xiaozhengkeji.mchttpapi.tools.Mes;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;

import java.io.*;

public final class McHttpAPI extends JavaPlugin {
    public String springboot;
    public Process ps;
    public Integer springBootPort;
    public String key;

    @Override
    public void onLoad() {
        //创建config.yml
        saveDefaultConfig();
        //创建网站
        saveResource("springboot.jar", false);
        springboot = new File("./plugins/McHttpAPI", "springboot.jar").getAbsolutePath();
    }

    @Override
    public void onEnable() {
        // Plugin startup logic
        springBootPort = getConfig().getInt("SpringBoot.Port");
        key = getConfig().getString("SpringBoot.Key");
        Mes.logServer("开始构建网站驱动! : " + springboot);
        new BukkitRunnable() {
            @Override
            public void run() {
                springBoot();
                readProcessOutput(ps);
            }
        }.runTaskAsynchronously(this);
        Mes.logServer("构建网站驱动完成!");
        Mes.logServer("开始构建服务端");
        new BukkitRunnable() {
            @Override
            public void run() {
                TcpServer tcpServer = new TcpServer(getConfig().getInt("MCServer.Port"));
                tcpServer.talk();
            }
        }.runTaskAsynchronously(this);
        Mes.logServer("构建服务端完成!");
    }

    @Override
    public void onDisable() {
        // Plugin shutdown logic
        ps.destroy();
        Mes.logServer("关闭网站驱动成功!");
    }

    void springBoot() {
        try {
            ps = Runtime.getRuntime().exec(new String[]{"java", "-jar", springboot, "--server.port=" + springBootPort, String.valueOf(getConfig().getInt("MCServer.Port")), key});
            Mes.logServer("构建网站驱动成功!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 打印进程输出
     *
     * @param process 进程
     */
    private static void readProcessOutput(final Process process) {
        // 将进程的正常输出在 System.out 中打印，进程的错误输出在 System.err 中打印
        read(process.getInputStream(), System.out);
        read(process.getErrorStream(), System.err);
    }

    // 读取输入流
    private static void read(InputStream inputStream, PrintStream out) {
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            while ((line = reader.readLine()) != null) {
                out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
